package org.xa3apm.vote.bean;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import org.xa3apm.vote.hibernate.entities.Municipality;
import org.xa3apm.vote.hibernate.entities.Person;
import org.xa3apm.vote.hibernate.entities.Province;
import org.xa3apm.vote.hibernate.entities.Settlement;

@Stateless
public class EntityManagerBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2631581189508811507L;

	public EntityManagerBean() {
		super();
	}

	@PersistenceUnit(unitName = "vote")
	private EntityManagerFactory emf;

	public <T> void create(T... entityes) {
		for (T entity : entityes) {
			EntityManager em = emf.createEntityManager();
			em.persist(entity);
		}
	}

	public Province getProvinceById(Long id) {
		EntityManager em = emf.createEntityManager();
		return (Province) (em.createNamedQuery("Province.getById")
				.setParameter("id", id).getSingleResult());
	}

	@SuppressWarnings("unchecked")
	public List<Province> getProvinceAll() {
		EntityManager em = emf.createEntityManager();
		List<Province> resultList = em.createNamedQuery("Province.getAll")
				.getResultList();
		return resultList;
	}

	public Municipality getMunicipalityById(Long id) {
		EntityManager em = emf.createEntityManager();
		return (Municipality) (em.createNamedQuery("getMunById").setParameter(
				"munId", id).getSingleResult());
	}

	@SuppressWarnings("unchecked")
	public List<Municipality> getMunicipalityAll() {
		EntityManager em = emf.createEntityManager();
		List<Municipality> resultList = em.createNamedQuery(
				"Municipality.getAll").getResultList();
		return resultList;
	}

	@SuppressWarnings("unchecked")
	public List<Municipality> getMunProvAll(Long id) {
		EntityManager em = emf.createEntityManager();
		List<Municipality> resultList = em
				.createNamedQuery("Municipality.getAllByProvinceId")
				.setParameter("provinceId", id).getResultList();
		return resultList;
	}

	public Person getPersonById(Long id) {
		EntityManager em = emf.createEntityManager();
		return (Person) (em.createNamedQuery("Person.getById").setParameter(
				"id", id).getSingleResult());
	}

	@SuppressWarnings("unchecked")
	public List<Person> getPersonAll() {
		EntityManager em = emf.createEntityManager();
		return em.createNamedQuery("Person.getAll").getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Settlement> getSettlementMunicipalityAll(Long id) {
		EntityManager em = emf.createEntityManager();
		return em.createNamedQuery("Settlement.getByMunicipalityId")
				.setParameter("municipality", id).getResultList();
	}
}
